package com.i2bt.app.login;

import com.i2bt.common.AndroidRestContract;

import com.i2bt.R;
import com.i2bt.app.BaseActivity;
import com.i2bt.app.login.model.LoginJsonHandle;
import com.i2bt.app.main.MainActivity;
import com.i2bt.bean.LoginBean;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.File;
import java.io.IOException;

public class LoginActivity extends BaseActivity implements TextWatcher {
	private Button login_button;
	private EditText userName, password;
	private TextView toRegist, forgetPassword, warnToast;
	private String userNameStr, passwordStr;

	/**
	 * 点击空白处隐藏输入法
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		InputMethodManager manager;
		manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null
					&& getCurrentFocus().getWindowToken() != null) {
				manager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}

	/**
	 * 初始化页面
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		if (Build.VERSION.SDK_INT < 11) {
			actionBarSupport.hide();
		}
		if (this.readXML("ACCOUNT", "USERID") != null) {
			this.goActivityAndFinish(MainActivity.class);
		}
		setContentView(R.layout.activity_login);
		initView();
		this.userName.setText("i3bt");
		this.password.setText("qawsedrf");

		String defultDownloadPath = "/sdcard";
		String downloadPath = readXML("SETTING", "SHOWPATH");
		if (downloadPath == null) {
			File index = Environment.getExternalStorageDirectory();
			if (index.exists()) {
				File p = new File(index.getPath() + "/Download");
				if (!p.exists()) {
					try {
						if (p.createNewFile()) {
							defultDownloadPath = p.getPath();
						} else {
							defultDownloadPath = index.getPath();
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			} else {
				File phone = Environment.getRootDirectory();
				System.out.println(phone.getPath().toString());
				File p = new File(phone.getPath() + "/Download");
				if (!p.exists()) {
					try {
						if (p.createNewFile()) {
							defultDownloadPath = p.getPath();
						} else {
							defultDownloadPath = phone.getPath();
						}
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			downloadPath = defultDownloadPath;
			this.writeXML("SETTING", "SHOWPATH", "/Download");
			this.writeXML("SETTING", "DOWNLOADPATH", downloadPath);
		}

	}

	/**
	 * 点击事件，登陆按钮，注册和忘记密码使用
	 */
	@Override
	public void onClick(View v) {
		if (v == login_button) {
			warnToast.setVisibility(View.INVISIBLE);
			userNameStr = userName.getText().toString();
			passwordStr = password.getText().toString();
			logic();
		} else if (v == toRegist) {
			this.goActivity(RegistActivty.class);
		} else if (v == forgetPassword) {
			toastHandler("抱歉，此功能尚未开发！");
		}
	}

	/**
	 * 初始化视图，获取空间并添加事件监听
	 */
	protected void initView() {
		login_button = (Button) this.findViewById(R.id.login_Button);
		userName = (EditText) this.findViewById(R.id.login_UserName);
		password = (EditText) this.findViewById(R.id.login_password);
		toRegist = (TextView) this.findViewById(R.id.login_toRegist);
		forgetPassword = (TextView) this
				.findViewById(R.id.login_forgetPassword);
		warnToast = (TextView) this.findViewById(R.id.login_Toast);
		login_button.setOnClickListener(this);
		toRegist.setOnClickListener(this);
		forgetPassword.setOnClickListener(this);
		password.addTextChangedListener(this);
		userName.addTextChangedListener(this);
	}

	/**
	 * 处理登陆按钮的输入判断和做出登陆操作
	 */
	protected void logic() {
		if (userNameStr.length() == 0) {
			showWarnToast("用户名不能为空");
		} else if (passwordStr.length() == 0) {
			showWarnToast("密码不能为空");
		} else if (passwordStr.length() < 6) {
			showWarnToast("密码长度不对,最小需要六位");
		} else {
			new LoginJsonHandle(this).postTo(AndroidRestContract.REST_LOGIN,
					loginBean(userNameStr, passwordStr));
		}
	}

	/**
	 * 新建登陆用 bean
	 * 
	 * @param use
	 *            用户名
	 * @param pass
	 *            密码
	 */
	private LoginBean loginBean(String use, String pass) {
		LoginBean bean = new LoginBean();
		bean.setAct(AndroidRestContract.LOGIN);
		bean.setUserId(use);
		bean.setPassword(pass);
		return bean;
	}

	/**
	 * 显示警告信息
	 * 
	 * @param Str显示的信息
	 */
	public void showWarnToast(String Str) {
		warnToast.setText(Str);
		warnToast.setVisibility(View.VISIBLE);
	}

	@Override
	public void afterTextChanged(Editable arg0) {
		// TODO Auto-generated method stub
		if (arg0.length() > 0) {
			int pos = arg0.length() - 1;
			char c = arg0.charAt(pos);
			if (c == ' ' || c == '.') {
				arg0.delete(pos, pos + 1);
				toastHandler("输入违法!");
			}
		}
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		if (warnToast.getVisibility() == View.VISIBLE) {
			if ((!password.getText().toString().equals(""))
					&& (!userName.getText().toString().equals(""))) {
				warnToast.setVisibility(View.INVISIBLE);
			}
		}
	}

	public String getUserNameStr() {
		return userNameStr;
	}

	public String getPasswordStr() {
		return passwordStr;
	}

	@Override
	public void backHomeOperate() {
		// TODO Auto-generated method stub

	}

}
